package setting

import (
	"gin-mvc/constants"
	"gin-mvc/pkg/util"
	"github.com/go-ini/ini"
	"log"
	"os"
	"time"
)

var (
	Cfg             *ini.File
	AppSetting      = &App{}
	ServerSetting   = &Server{}
	DatabaseSetting = &Database{}
	RedisSetting    = &Redis{}
	CronSetting     = &Cron{}
	JobSetting      = &Job{}
)

type (
	App struct {
		AppName  string
		PageSize int
	}

	Cron struct {
		Enable bool
	}

	Database struct {
		Type        string
		User        string
		Password    string
		Host        string
		Name        string
		TablePrefix string
	}

	Server struct {
		RunMode      string
		HttpPort     int
		ReadTimeout  time.Duration
		WriteTimeout time.Duration
	}

	Redis struct {
		Host        string
		Password    string
		MaxIdle     int
		MaxActive   int
		IdleTimeout time.Duration
	}

	Job struct {
		Enable        bool
		JobCount      int
		ConsumerCount int
	}
)

func initPath() {
	isExit, err := util.PathExists(util.ProjectPath() + "config")
	if err != nil {
		log.Fatal(err)
	}
	if !isExit {
		if err := os.MkdirAll(util.ProjectPath()+"config", os.ModePerm); err != nil {
			log.Fatal(err)
		}
	}
}

func Setup() {
	initPath()
	var err error
	path := util.ProjectPath()
	Cfg, err = ini.Load(path + constants.ConfigPath)
	if err != nil {
		log.Fatalf("Fail to parse `config/app.ini`: %v\n", err)
	}

	// 注册配置项
	mapTo("app", AppSetting)
	mapTo("server", ServerSetting)
	mapTo("database", DatabaseSetting)
	mapTo("redis", RedisSetting)
	mapTo("cron", CronSetting)
	mapTo("job", JobSetting)

	ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
	ServerSetting.WriteTimeout = ServerSetting.WriteTimeout * time.Second
	RedisSetting.IdleTimeout = RedisSetting.IdleTimeout * time.Second
}

// mapTo map section
func mapTo(section string, v interface{}) {
	err := Cfg.Section(section).MapTo(v)
	if err != nil {
		log.Fatalf("Cfg.MapTo %s err: %v", section, err)
	}
}
